import {
  createRouter,
  createWebHistory,
  createWebHashHistory
} from "vue-router";
import { setupLayouts } from "virtual:generated-layouts";
import generatedRoutes from "virtual:generated-pages";
import usePageStore from "@/store/modules/usePageStore";
import useUserStore from "@/store/modules/useUserStore";
import NProgress from "@/utils/nprogress";
import useRem from "@/hooks/useRem";
import type { RouteLocationNormalized } from "vue-router";

// const routes:RouteRecordRaw[]=[
//   { path: '/', component: () =>import(/* webpackChunkName: "main" */ '@/views/Login.vue') }
// ]
const routes = setupLayouts(generatedRoutes);
console.log("routes:", routes);
console.log("env:", VITE_ENV);
const PAGE_CACHE = VITE_ENV.VITE_PAGE_CACHE;
const router = createRouter({
  history:
    VITE_ENV.VITE_ROUTE_MODE === "hash"
      ? createWebHashHistory()
      : createWebHistory(VITE_ENV.VITE_PUBLIC_PATH),
  routes
});
const cachePages = name => {
  const pageStore = usePageStore();
  const time = new Date().getTime();
  pageStore.removeExpireCache();
  if (pageStore.hasCachePage(name)) return;
  pageStore.addCachePage({
    name,
    time
  });
};
router.beforeEach((to, from, next) => {
  // 返回 false 以取消导航
  NProgress.start();
  const userStore = useUserStore();
  if (PAGE_CACHE && to.meta.cache) cachePages(to.name);
  const roles = userStore.roles;
  const token = userStore.token;
  useRem(to.meta.pxtorem);
  if (to.meta.auth && !token) {
    next({
      name: "login",
      query: {
        to: to.path
      }
    });
    return false;
  }
  const authPass = roles.some(r => to.meta.roles?.includes(r));
  if (to.meta.roles && !authPass) {
    next({
      name: "error-403"
    });
    return false;
  }
  next();
});
router.afterEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized, failure) => {
    NProgress.done();
  }
);
export default router;
